package com.media.selector.media.preview

import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.media.selector.BR
import com.media.selector.MediaSelector
import com.media.selector.R
import com.media.selector.databinding.FragmentMediaPreviewBinding
import com.media.selector.media.model.entity.MediaEntity
import com.media.selector.widget.imagezoom.ImageViewTouchBase

/**
 * date        ：2020/5/11
 * author      ：蒙景博
 * description ：
 */
class MediaPreviewFragment : Fragment() {

    companion object {
        private const val EXTRA_RESULT_BUNDLE = "extra_result_bundle"
        fun with(media: MediaEntity): MediaPreviewFragment {
            return MediaPreviewFragment().apply {
                arguments = Bundle().apply {
                    putParcelable(EXTRA_RESULT_BUNDLE, media)
                }
            }
        }
    }

    private var mMedia: MediaEntity? = null
    private lateinit var mBinding: FragmentMediaPreviewBinding

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_media_preview, container, false)
        mBinding.lifecycleOwner = this
        mBinding.setVariable(BR.data, this)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.mediaPreviewImageZoom.displayType = ImageViewTouchBase.DisplayType.FIT_TO_SCREEN
        mBinding.mediaPreviewVideoPlay.setOnClickListener {
            try {
                startActivity(Intent(Intent.ACTION_VIEW).setDataAndType(mMedia?.contentUri, "video/*"))
            } catch (e: ActivityNotFoundException) {
                Toast.makeText(context, R.string.error_no_video_activity, Toast.LENGTH_SHORT).show();
            }
        }
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mMedia = arguments?.getParcelable(EXTRA_RESULT_BUNDLE)
        mMedia?.let {
            // 除视频以外，其他均可缩放
            mBinding.mediaPreviewImageZoom.setScaleEnabled(!it.isVideo())
            mBinding.mediaPreviewImageZoom.doubleTapEnabled = !it.isVideo()
            // 加载资源
            MediaSelector.with().load(it.contentUri)?.image(mBinding.mediaPreviewImageZoom)
            // 如果是视频，则显示播放按钮
            mBinding.mediaPreviewVideoPlay.visibility = if (it.isVideo()) View.VISIBLE else View.GONE
        }
    }

    fun getMedia(): MediaEntity? = mMedia
}